package com.example.my_test_2.controller;



import com.example.my_test_2.dto.MerchantDto;
import com.example.my_test_2.dto.UserDto;
import com.example.my_test_2.pojo.Role;
import com.example.my_test_2.pojo.Shop;
import com.example.my_test_2.pojo.User;
import com.example.my_test_2.repos.RoleRepository;
import com.example.my_test_2.repos.ShopRepository;
import com.example.my_test_2.repos.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("api/merchant")
public class MerchantController {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private ShopRepository shopRepository;

    @Autowired
    private RoleRepository roleRepository;

    @PostMapping("/register")
    public User registerMerchant(@RequestBody MerchantDto merchantDto) {

        /// 创建Role对象，假设所有注册的商家都是"商户"角色
        Role role = new Role();
        role.setRoleId(2);
        role.setRoleName("商户");

        // 先保存Role对象
        role = roleRepository.save(role);


        // 创建User对象
        User user = new User();
        user.setUserName(merchantDto.getUserName());
        user.setUserPwd(merchantDto.getUserPwd());
        user.setRole(role); // 设置已保存的Role对象

        // 创建Shop对象
        Shop shop = new Shop();
        shop.setShopName(merchantDto.getShopName());
        shop.setUser(user); // 关联User对象

        // 保存User和Shop
        userRepository.save(user);
        shopRepository.save(shop);

        return user;
    }


    @PostMapping("/login")
    public User merchantLogin(@RequestBody UserDto userDto) {
        User user = userRepository.findByUserName(userDto.getUserName());
        if (user != null && user.getUserPwd().equals(userDto.getUserPwd()) && "商户".equals(user.getRole().getRoleName())) {
            return user; // 用户存在，密码正确，且是商家
        } else {
            return null; // 登录失败，返回null
        }
    }
}

